package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Value("${sky.salt}")
    private String salt;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        // 2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 密码比对
        password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!password.equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void createEmployee(EmployeeDTO employeeDTO) {
        // 判断用户是否已存在
        Employee emp = employeeMapper.getByUsername(employeeDTO.getUsername());
        if (emp != null) {
            throw new BaseException(employeeDTO.getUsername() + MessageConstant.ALREADY_EXISTS);
        }

        // 新增用户
        emp = new Employee();
        BeanUtils.copyProperties(employeeDTO, emp);
        emp.setPassword(DigestUtils.md5DigestAsHex((PasswordConstant.DEFAULT_PASSWORD + salt).getBytes()));
        emp.setStatus(StatusConstant.ENABLE);
        log.info("Get emp: {}", emp);
        employeeMapper.save(emp);
    }

    /**
     * 员工列表分页模糊查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page page = (Page) employeeMapper.page(employeePageQueryDTO.getName());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 启用或禁用员工
     *
     * @param status
     * @param id
     */
    @Override
    public void pickOrBan(Integer status, Long id) {
        // 校验数据合法性：用户是否存在、是否是启用状态启用或禁止状态禁止
        Employee emp = employeeMapper.getByUserId(id);
        log.info("Get emp: {}", emp);
        if (emp == null || emp.getId() == null || emp.getStatus().equals(status)) {
            throw new BaseException(MessageConstant.UNKNOWN_ERROR);
        }

        // 执行更改状态操作
        emp.setStatus(status);
        employeeMapper.updateStatusByUserId(emp);
    }

    /**
     * 员工修改密码
     *
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        // 校验数据合法性
        Employee emp = employeeMapper.getByUserId(BaseContext.getCurrentId());
        if (emp == null || emp.getId() == null) {
            throw new BaseException(MessageConstant.UNKNOWN_ERROR);
        }

        // 校验密码
        if (!DigestUtils.md5DigestAsHex((passwordEditDTO.getOldPassword() + salt).getBytes()).equals(emp.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        // 更新密码
        emp.setPassword(DigestUtils.md5DigestAsHex((passwordEditDTO.getNewPassword() + salt).getBytes()));
        employeeMapper.updatePasswordByUserId(emp);
    }

    /**
     * 根据员工id获取员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee getEmployeeById(Long id) {
        return employeeMapper.getByUserId(id);
    }

    /**
     * 根据员工id修改员工信息
     *
     * @param employeeDTO
     */
    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        Employee emp = new Employee();
        BeanUtils.copyProperties(employeeDTO, emp);
        employeeMapper.update(emp);
    }

}
